package org.liang.auth.Interceptors;

import org.liang.base.annotation.RonghuaPermission;
import org.liang.base.context.LoginContext;
import org.liang.system.domain.Employee;
import org.liang.system.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private IEmployeeService employeeService;

    //拦截所有请求
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("----------------------------");
        //获取token
        String token = request.getHeader("token");
        System.out.println(token);
        //根据token获取user
        Employee user = (Employee) LoginContext.loginMap.get(token);
        if(Objects.isNull(user)){
            response.getWriter().print("{\"msg\":\"NoLogin\",\"success\": false}");
            return false;
        }
        //鉴权
        //判断当前资源是否需要权限
        HandlerMethod method = (HandlerMethod) handler;
        Method method1 = method.getMethod();
        RonghuaPermission annotation = method1.getAnnotation(RonghuaPermission.class);
        if(Objects.isNull(annotation)){
            return true;
        }
        //拿到类名
        String simpleName = method.getBeanType().getSimpleName();
        //拿到方法名
        String method1Name = method1.getName();
        //获取资源权限----sn
        String methodPermission = simpleName + ":" + method1Name;

        //获取用户权限
        List<String> sns = employeeService.selectPermissionSnsById(user.getId());
        //比较用户权限和资源权限
        if(!sns.contains(methodPermission)){
            //没有权限
            response.getWriter().print("{\"msg\":\"NoPermission\",\"success\": false}");
            return false;
        }

        return true;
    }
}
